﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace Tensop.Net.Core
{
    public class MemoryManager
    {
        Stack<byte[]> Pool;
        int maxCount;
        public MemoryManager(int max)
        {
            Pool = new Stack<byte[]>( max * 3 );
            maxCount = max * 3;
        }

        public void InitBuffer()
        {
            for ( int i = 0; i < maxCount; i++ )
            {
                Pool.Push( new byte[4096] );
            }
        }

        public ArraySegment<byte> Pop(SocketAsyncEventArgs e)
        {
            byte[] data;
            lock ( Pool )
            {
                data = Pool.Pop();
            }
            Array.Copy( e.Buffer, e.Offset, data, 0, e.BytesTransferred );
            return new ArraySegment<byte>( data, e.Offset, e.BytesTransferred );
        }

        public void Push(ArraySegment<byte> data)
        {
            if ( data.Array.Length != 4096 )
                return;
            lock ( Pool )
            {
                Pool.Push( data.Array );
            }
        }
    }
}
